document.addEventListener('DOMContentLoaded', function() {
    // 清空搜索框的默认值并防止自动填充
    const searchInput = document.getElementById('mainSearchInput');
    if (searchInput) {
        searchInput.value = '';
        // 延迟清空，确保在浏览器自动填充后执行
        setTimeout(() => {
            searchInput.value = '';
        }, 100);
        setTimeout(() => {
            searchInput.value = '';
        }, 500);
        
        // 监听输入事件，防止自动填充
        searchInput.addEventListener('input', function() {
            // 如果检测到可能是自动填充的内容，清空它
            if (this.value && !this.dataset.userTyped) {
                setTimeout(() => {
                    if (!this.dataset.userTyped) {
                        this.value = '';
                    }
                }, 50);
            }
        });
        
        // 标记用户手动输入
        searchInput.addEventListener('keydown', function() {
            this.dataset.userTyped = 'true';
        });
        
        // 重置标记
        searchInput.addEventListener('blur', function() {
            setTimeout(() => {
                delete this.dataset.userTyped;
            }, 1000);
        });
    }
    
    // 页面切换

    document.getElementById('backToSearchButton').addEventListener('click', showSearchPage);
    
    // 主搜索功能
    document.getElementById('mainSearchButton').addEventListener('click', handleMainSearch);
    document.getElementById('mainSearchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            handleMainSearch();
        }
    });
    
    // 初始化页面
    showSearchPage();
});



// 显示搜索页面
function showSearchPage() {
    document.getElementById('searchPage').classList.remove('d-none');
    document.getElementById('uploadPage').classList.add('d-none');
    document.body.style.background = 'linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%)';
}

// 主搜索处理
function handleMainSearch() {
    const keyword = document.getElementById('mainSearchInput').value.trim();
    if (!keyword) {
        alert('请输入搜索关键词');
        return;
    }
    
    searchByKeyword(keyword, 'mainSearchResultsList', 'mainSearchResults');
}

// 按关键词搜索
function searchByKeyword(keyword, resultsListId, resultsContainerId) {
    showLoading(resultsListId);
    document.getElementById(resultsContainerId).classList.remove('d-none');
    
    fetch(`/api/search?keyword=${encodeURIComponent(keyword)}`)
        .then(response => response.json())
        .then(data => {
            displaySearchResults(data, resultsListId);
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById(resultsListId).innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    搜索失败: ${error.message || '未知错误'}
                </div>
            `;
        });
}

// 从上传页面搜索关键词
function searchFromUpload(keyword) {
    document.getElementById('mainSearchInput').value = keyword;
    showSearchPage();
    setTimeout(() => {
        handleMainSearch();
    }, 300);
}

// 显示搜索结果
function displaySearchResults(data, resultsListId) {
    const container = document.getElementById(resultsListId);
    const countElement = document.getElementById('searchResultCount');
    
    if (data.error) {
        container.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-exclamation-triangle me-2"></i>
                ${data.error}
            </div>
        `;
        return;
    }
    
    // 检查结果格式，适配新的API返回格式
    let contentResults = [];
    let commentResults = [];
    let totalResults = 0;
    
    // 处理新格式的搜索结果
    if (data.results && typeof data.results === 'object' && !Array.isArray(data.results)) {
        contentResults = data.results.content || [];
        commentResults = data.results.comments || [];
        totalResults = contentResults.length + commentResults.length;
    } 
    // 处理旧格式的搜索结果（向后兼容）
    else if (Array.isArray(data.results)) {
        contentResults = data.results;
        totalResults = contentResults.length;
    }
    
    if (totalResults === 0) {
        container.innerHTML = `
            <div class="alert alert-info">
                <i class="bi bi-info-circle me-2"></i>
                没有找到匹配的内容
            </div>
        `;
        if (countElement) countElement.textContent = '0 个结果';
        return;
    }
    
    if (countElement) {
        countElement.textContent = `${totalResults} 个结果`;
    }
    
    let resultsHtml = '';
    
    // 如果有内容结果，先显示内容结果
    if (contentResults.length > 0) {
        resultsHtml += `
            <div class="search-section mb-4">
                <h4 class="search-section-title">
                    <i class="bi bi-file-text me-2"></i>内容匹配 (${contentResults.length})
                </h4>
                <div class="search-section-items">
        `;
        
        contentResults.forEach(item => {
            resultsHtml += generateContentItemHtml(item);
        });
        
        resultsHtml += `
                </div>
            </div>
        `;
    }
    
    // 如果有评论结果，显示评论结果
    if (commentResults.length > 0) {
        resultsHtml += `
            <div class="search-section mb-4">
                <h4 class="search-section-title">
                    <i class="bi bi-chat-dots me-2"></i>评论匹配 (${commentResults.length})
                </h4>
                <div class="search-section-items">
        `;
        
        commentResults.forEach(item => {
            resultsHtml += generateCommentResultHtml(item);
        });
        
        resultsHtml += `
                </div>
            </div>
        `;
    }
    
    container.innerHTML = resultsHtml;
}
